import logging
import os
import traceback

import requests
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

from api_test.common.api_response import JsonResponse
from api_server.utils import *

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。

account_message_info = {}
pb2parse("dragonmaze", os.path.dirname(os.path.abspath(__file__)) + "/proto/account_message.proto", account_message_info)


class DragonmazeAccount(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    @swagger_auto_schema(request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        required=['url', 'body'],
        properties={
            'url': openapi.Schema(type=openapi.TYPE_STRING, description="url地址 eg.http://xxx.com/account"),
            'body': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数"),
            'login': openapi.Schema(type=openapi.TYPE_OBJECT, description="请求参数，body参数依赖的登录请求参数"),
        },
    ))
    def post(self, request):
        """
        dragonMaze http+protobuf
        """
        try:
            data = JSONParser().parse(request)

            trans_name = data["body"]["name"]

            raw_data = pb2seria(account_message_info, data["body"])

            url = data["url"]
            result = requests.post(url, data=raw_data)
            resp_name = int(trans_name) + 1
            message = eval(account_message_info[str(resp_name)])()
            message.ParseFromString(result.content)

            json_dict = pb2dict(message)

            return JsonResponse(data={
                "data": json_dict, "status": str(result.status_code) + " " + str(result.reason)
            }, code="999999", msg="成功")
        except Exception as e:
            return JsonResponse(code="999990", msg="失败", data={"error": str(e)})

